<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_fetchDictList"
    :columns="columns"
    :row-selection="rowSelection"
    row-key="dictId"
    :onValuesChange="onValuesChange"
  >
    <template #toolbars>
      <Row class="w-full mr-3">
        <Col :span="16">
          <Space>
            <b-button icon="add" @click="onAdd" code="system:dict:add"
              >新增</b-button
            >
            <b-button
              icon="delete"
              @click="() => onDelete()"
              :disabled="!selectKeys?.length"
              code="system:dict:remove"
              >删除</b-button
            >
          </Space>
        </Col>
        <Col :span="8" class="text-right content-center">
          <Space>
            <b-button icon="export" code="system:dict:export" @click="onExport"
              >导出</b-button
            >
          </Space>
        </Col>
      </Row>
    </template>
    <template #operation="{ record }">
      <b-button icon="detail" type="link" @click="() => onView(record)"
        >详情</b-button
      >
      <b-button
        icon="del"
        type="link"
        @click="() => onDelete(record.dictId)"
        code="system:dict:remove"
        >删除</b-button
      >
    </template>
  </ProTable>
  <FormModal :items="items"> </FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { Col, Modal, Row, Space, Tag } from 'ant-design-vue';
import dayjs from 'dayjs';
import { RouterLink } from 'vue-router';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { download, listToEnum, listToOption } from '@/utils/utils';
import {
  createDict,
  deleteDict,
  exportDict,
  fetchDictList,
  fetchSysNormalDisable,
  updateDict,
} from '@/api/system';
import { hasPermission } from '../../../permission';

defineOptions({
  name: 'dict',
});
const _fetchDictList = async (params: any) => {
  params.params = {
    beginTime: params.time?.[0],
    endTime: params.time?.[1],
  };
  const res = await fetchDictList(params);
  return res;
};
const tableRef = ref();

const sysNormalDisableOptions = ref<Global.Option[]>([]);
const sysNormalDisableEnum = ref<Record<string, any>>([]);

const init = () => {
  fetchSysNormalDisable().then((res) => {
    sysNormalDisableOptions.value = listToOption(
      res.data,
      'dictLabel',
      'dictValue',
    ) as Global.Option[];
    sysNormalDisableEnum.value = listToEnum(res.data, 'dictValue', 'dictLabel');
  });
};

init();

const selectKeys = ref<number[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values) {
      selectKeys.value = values as number[];
    },
  };
});

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '字典编号',
    dataIndex: 'dictId',
    hideInSearch: true,
  },
  {
    title: '字典名称',
    dataIndex: 'dictName',
  },
  {
    title: '字典类型',
    dataIndex: 'dictType',
    customRender({ text }) {
      return (
        <RouterLink
          class=' text-blue-700'
          to={`/system/dict-detail?dictType=${text}`}
        >
          {text}
        </RouterLink>
      );
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueEnum: {
      ...sysNormalDisableEnum.value,
    },
    customRender({ text }) {
      return (
        <Tag color={text === '1' ? 'error' : 'success'}>
          {sysNormalDisableEnum.value[text] || ''}
        </Tag>
      );
    },
  },
  {
    title: '备注',
    dataIndex: 'remark',
    hideInSearch: true,
  },
  {
    title: '创建时间',
    dataIndex: 'time',
    isTime: true,
    hideInTable: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 200,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '字典名称',
    type: 'input',
    field: 'dictName',
    rules: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    props: {
      placeholder: '请输入名称',
    },
  },
  {
    label: '字典类型',
    type: 'input',
    rules: [{ required: true, message: '请输入字典类型', trigger: 'blur' }],
    field: 'dictType',
    props: {
      placeholder: '请输入字典类型',
    },
  },
  {
    label: '状态',
    type: 'radio',
    field: 'status',
    props: {
      options: sysNormalDisableOptions.value,
    },
  },
  {
    label: '备注',
    type: 'textarea',
    field: 'remark',
    props: {
      placeholder: '请输入备注',
      maxlength: 200,
      showCount: true,
    },
  },
]);

const { FormModal, open } = useFormModal({ size: 'small' });

const onAdd = async () => {
  open({
    title: '新增',
    defaultValue: {
      status: '0',
    },
    serviceApi: async (params: any): Promise<any> => {
      await createDict(params);
      sleep(() => tableRef.value.refresh());
    },
  });
};

const onView = async (record: any) => {
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: {
      ...record,
    },
    hasEditPermission: hasPermission('system:dict:edit'),
    serviceApi: async (params: any): Promise<any> => {
      await updateDict({
        ...params,
      });
      sleep(() => tableRef.value.refresh());
    },
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
const onDelete = async (id?: number) => {
  const ids = id ? [id] : selectKeys.value;

  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选项？`,
    centered: true,
    onOk: async () => {
      await deleteDict(ids);
      sleep(() => tableRef.value.refresh());
      selectKeys.value = [];
    },
  });
};

const searchParams = ref({});
const onValuesChange = (values: any) => {
  searchParams.value = Object.assign(searchParams.value, values);
};
const onExport = async () => {
  const res = await exportDict(searchParams.value);
  download(
    res as unknown as Blob,
    `data_${dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`,
  );
};
</script>
